package simple_monitor

import (
	"io/ioutil"
	"fmt"
	"net/http"
	"encoding/json"
)

type Config struct {
	Url string `json:"url"`
	ApiCode string `json:"api_code"`
	Region string `json:"region"`
	Server string `json:"server"`
	Debug bool `json:"debug"`
}

var config Config
var configInited bool

type Reporter struct {
	Type string
	Process string
}

func (this *Reporter) Report(args ...interface{}) {
	Init()

	values := ""
	for i := 0;i + 1 < len(args);i += 2 {
		if i > 0 {
			values += ","
		}
		values += fmt.Sprintf("%v,%v", args[i], args[i+1])
	}

	url := fmt.Sprintf(
		"%s?api_code=%s&region=%s&server=%s&type=%s&process=%s&value=%s",
		config.Url,
		config.ApiCode,
		config.Region,
		config.Server,
		this.Type,
		this.Process,
		values,
		)
	if config.Debug {
		fmt.Println(url)
	}

	resp, err := http.Get(url)
	if err != nil {
		if config.Debug {
			fmt.Println(err)
		}
		return
	}
	defer resp.Body.Close()

	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		if config.Debug {
			fmt.Println(err2)
		}
		return;
	}
	if config.Debug {
		fmt.Println(body)
	}
}

func Init() (ret *Config, errRet error) {
	ret = nil
	errRet = nil

	if configInited {
		return
	}

	configInited = true

		// 解析配置文件的内容
	if bFile, err := ioutil.ReadFile("/etc/simple_monitor.json"); err != nil {
		errRet = err
		return
	} else if err := json.Unmarshal(bFile, &config); err != nil {
		errRet = err
		return
	}

	if config.Url == "" {
		config.Url = "http://monitor.pandabtc.cn:2345/monitor/report"
	}

	ret = &config
	return
}



